package io.github.loserYa.mutil;

import org.springframework.amqp.core.AcknowledgeMode;
import org.springframework.amqp.rabbit.config.SimpleRabbitListenerContainerFactory;
import org.springframework.amqp.rabbit.connection.CachingConnectionFactory;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitAdmin;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.util.StringUtils;

/**
 * 抽象的 mq 多数数据源
 *
 * @author loser
 * @date 2024/4/25
 */
public abstract class AbstractFactory {

    public ConnectionFactory buildConnectionFactory(String host, Integer port, String username, String password, String virtualHost) {
        CachingConnectionFactory connectionFactory = new CachingConnectionFactory();
        connectionFactory.setHost(host);
        connectionFactory.setPort(port);
        connectionFactory.setUsername(username);
        connectionFactory.setPassword(password);
        if (StringUtils.isEmpty(virtualHost)) {
            virtualHost = "/";
        }
        connectionFactory.setVirtualHost(virtualHost);
        return connectionFactory;
    }

    public SimpleRabbitListenerContainerFactory buildContainerFactory(ConnectionFactory connectionFactory, String module) {
        SimpleRabbitListenerContainerFactory factory = new SimpleRabbitListenerContainerFactory();
        factory.setConnectionFactory(connectionFactory);
        AcknowledgeMode acknowledgeMode;
        if (StringUtils.isEmpty(module)) {
            acknowledgeMode = AcknowledgeMode.valueOf(module);
        } else {
            acknowledgeMode = AcknowledgeMode.MANUAL;
        }
        factory.setAcknowledgeMode(acknowledgeMode);
        return factory;
    }

    public RabbitTemplate buildRabbitTemplate(ConnectionFactory connectionFactory) {
        return new RabbitTemplate(connectionFactory);
    }

    public RabbitAdmin buildRabbitAdmin(ConnectionFactory connectionFactory) {
        RabbitAdmin rabbitAdmin = new RabbitAdmin(connectionFactory);
        rabbitAdmin.setAutoStartup(true);
        return rabbitAdmin;
    }

}
